package com.quanquan.store.controller.marketActivity;

import DTO.user.UserDTO;
import DTO.user.UserInfoDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.quanquan.store.dto.ConsumeDTO;
import com.quanquan.store.dto.CouponDTO;
import com.quanquan.store.dto.IdDTO;
import com.quanquan.store.dto.marketActivity.CollectCardDTO;
import com.quanquan.store.entity.marketActivity.GiftTypeEnum;
import com.quanquan.store.entity.marketActivity.collectCards.*;
import com.quanquan.store.request.CouponRequest;
import com.quanquan.store.request.marketActivity.CollectCardsRequest;
import com.quanquan.store.service.CouponService;
import com.quanquan.store.service.marketActivity.CollectCardsService;
import enums.ResCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import utils.DateUtils;
import utils.HttpUtils;
import utils.StringUtil;
import utils.StringUtils;
import web.response.ResultBody;

import java.util.*;

/**
 * @ClassName CollectCardsController
 * @Description
 * @Author Owen
 * @Date 2019/9/19 0019 下午 6:07
 * @Version V1.0
 **/
@RestController
@RequestMapping("/marketActivity/collectCards")
@Slf4j
public class CollectCardsController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CollectCardsService collectCardsService;

    @Autowired
    private CouponService couponService;

    /**
     * 获取游戏信息
     * @param request
     * @return
     */
    @PostMapping("/getActivityInfo")
    public ResultBody getActivityInfo(@RequestBody CollectCardsRequest request) {

        if (null == request.getId() || StringUtils.isEmpty(request.getUserId())) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        CollectCards collectCards = collectCardsService.getById(request.getId());
        if (null == collectCards || collectCards.getStatus() != 1) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        //进行中
        Integer goingStatus = 0;
        if(DateUtils.compare_date(collectCards.getStartTime(),new Date()) > 0){
            goingStatus = -1;//未开始
        }
        if(DateUtils.compare_date(collectCards.getEndTime(),new Date()) <= 0){
            goingStatus = 1;//已结束
        }

        List<CollectCardsCard> allCards = collectCardsService.getAllCards(request.getId());

        IdDTO idDTO = new IdDTO();
        List<String> ids = new LinkedList<>();
        ids.add(request.getUserId());
        idDTO.setForeignKeyIds(ids);
        UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
        log.info("用户查询返回值："+ JSON.toJSONString(userInfoDTO));
        if(null != userInfoDTO && userInfoDTO.getUserDTOS().size() >= 1 && goingStatus == 0){
            UserDTO userDTO = userInfoDTO.getUserDTOS().get(0);
            if(null != userDTO && StringUtil.isNotEmpty(userDTO.getMemberCardNum())){
                String api = "http://xiaooo.quanquankeji.cn:10000/consume/getConsumeLst";
                Map<String,Object> param = new HashMap<>();
                param.put("cardCode",userDTO.getMemberCardNum());
                String postResult = HttpUtils.doPost(api, param);
                log.info("查询当天消费："+postResult);
                System.out.println("查询当天消费："+postResult);
                ResultBody resultBody = JSON.parseObject(postResult, ResultBody.class);
                if(null != resultBody && null != resultBody.getResCode() && resultBody.getResCode() == 0){
                    List<ConsumeDTO> list = JSONArray.parseArray(resultBody.getData().toString(),ConsumeDTO.class);
                    for (ConsumeDTO consume:list) {
                        List<CollectCardsRecord> listByConsumId = collectCardsService.getRecordListByConsumId(request.getId(), consume.getId());
                        if(listByConsumId.size() > 0){
                            continue;
                        }
                        int count = consume.getAmount().intValue()/188;
                        for (int i = 0; i < count; i++) {
                            addRandomCard(allCards,consume.getId(),request.getUserId(),request.getId());
                        }

                    }
                }
            }
        }
        List<CollectCardDTO> result = new LinkedList<>();
        for (CollectCardsCard card:allCards) {
            CollectCardDTO collectCardDTO = new CollectCardDTO();
            collectCardDTO.setCardId(card.getId());
            collectCardDTO.setCardName(card.getCardName());
            List<CollectCardsRecord> cardRecord = collectCardsService.getByUserIdAndCardId(request.getUserId(), card.getId());
            if(cardRecord.size() > 0){
                collectCardDTO.setCardImg(card.getFaceImg());
                collectCardDTO.setQuantity(cardRecord.size());
            }else{
                collectCardDTO.setCardImg(card.getBackImg());
                collectCardDTO.setQuantity(0);
            }
            result.add(collectCardDTO);
        }


        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", result);

    }

    /**
     * 兑换
     * @param request
     * @return
     */
    @PostMapping("/getActivityGift")
    public ResultBody getActivityGift(@RequestBody CollectCardsRequest request){
        if (null == request.getId() || StringUtils.isEmpty(request.getUserId())) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        CollectCards collectCards = collectCardsService.getById(request.getId());
        if (null == collectCards || collectCards.getStatus() != 1) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        if(DateUtils.compare_date(collectCards.getStartTime(),new Date()) > 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动未开始");
        }
        if(DateUtils.compare_date(collectCards.getEndTime(),new Date()) <= 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动已结束");
        }

        List<CollectCardsGiftRecord> userGiftRecord = collectCardsService.getUserGiftRecord(request.getId(), request.getUserId());
        if(userGiftRecord.size() > 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "您已兑换过奖品");
        }

        int countUserCards = collectCardsService.countUserCards(request.getId(), request.getUserId());
        if(countUserCards < 12){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "未满足兑换条件");
        }

        List<CollectCardsGift> gifts = collectCardsService.getGiftsByActivityIdForGame(request.getId());
        if(gifts.size() < 1){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "奖品已发完");
        }

        int randOdds = (int)(Math.random()*100 + 1);

        CollectCardsGift gift = null;
        int odds = 0;
        for (int i = 0; i < gifts.size(); i++) {
            odds += gifts.get(i).getOdds();
            if(odds >= randOdds){
                gift = gifts.get(i);
                break;
            }
        }

        System.out.println("随机奖品信息："+JSON.toJSONString(gift));
        String giftName = "";
        String giftImage = "";
        CollectCardsGiftRecord record = new CollectCardsGiftRecord();
        record.setUserId(request.getUserId());
        record.setActivityId(request.getId());
        record.setCreateTime(new Date());
        if(null == gift){
            record.setGiftType(GiftTypeEnum.NO_GIF.getCode());
        }else{
            GiftTypeEnum giftType = GiftTypeEnum.getGiftType(gift.getGiftType());
            switch (giftType){
                case COUPON_GIFT:
                    CouponRequest couponRequest = new CouponRequest();
                    couponRequest.setUserId(request.getUserId());
                    couponRequest.setId(gift.getCouponId());
                    String sendResult = couponService.sendCoupon(couponRequest);
                    System.out.println("发券结果："+sendResult);
                    if("发券成功".equals(sendResult)){
                        //扣减库存
                        collectCardsService.substractGiftStock(gift.getId());

                        try {
                            CouponDTO couponDTO = couponService.queryDetailsById(gift.getCouponId());
                            if(null != couponDTO){
                                giftName = couponDTO.getName();
                                giftImage = couponDTO.getImage();
                            }
                        }catch (Exception e){
                            System.out.println("券详情查询失败");
                        }
                        record.setGiftType(GiftTypeEnum.COUPON_GIFT.getCode());
                        record.setCouponId(gift.getCouponId());
                    }else{
                        record.setGiftType(GiftTypeEnum.NO_GIF.getCode());
                    }
                    break;
                case POINT_GIFT:
                    break;
                default:
                    record.setGiftType(GiftTypeEnum.NO_GIF.getCode());
                    break;
            }
        }

        record = collectCardsService.saveOrUpdateGiftRecord(record);
        Map<String,Object> result = new HashMap<>();
        result.put("giftName",giftName);
        result.put("giftImage",giftImage);
        result.put("giftType",record.getGiftType());

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success",result);

    }



    /**
     * 获取用户卡牌记录
     * @param request
     * @return
     */
    @PostMapping("/getUserCardsRecord")
    public ResultBody getUserCardsRecord(@RequestBody CollectCardsRequest request){
        if (null == request.getId() || StringUtils.isEmpty(request.getUserId())) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        CollectCards collectCards = collectCardsService.getById(request.getId());
        if (null == collectCards || collectCards.getStatus() != 1) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        int page = (null == request.getPage() ? 0 : request.getPage());
        int size = (null == request.getSize() ? 50 : request.getSize());

        List<CollectCardsRecord> list = collectCardsService.getUserCardsRecord(request.getId(), request.getUserId(), page, size);
        List<Object> result = new LinkedList<>();
        for (CollectCardsRecord record:list) {
            Map<String,Object> map = new HashMap<>();
            CollectCardsCard card = collectCardsService.getCardById(record.getCardId());
            map.put("cardName",card.getCardName());
            map.put("cardImg",card.getFaceImg());
            map.put("createTime", DateUtils.dateToString(record.getCreateTime(), DateUtils.TIMESTAMP));
            result.add(map);
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success",result);
    }


    public boolean addRandomCard(List<CollectCardsCard> allCards,String consumId,String userId,Long activityId){
        if(allCards.size() < 1){
            return false;
        }else{
            Random random = new Random();
            int i = random.nextInt(allCards.size());
            CollectCardsCard cardsCard = allCards.get(i);
            List<CollectCardsRecord> cardRecord = collectCardsService.getByUserIdAndCardId(userId, cardsCard.getId());
            if(cardRecord.size() >= 2){
                allCards.remove(i);
                return addRandomCard(allCards,consumId,userId,activityId);
            }else{
                CollectCardsRecord record = new CollectCardsRecord();
                record.setActivityId(activityId);
                record.setCardId(cardsCard.getId());
                record.setConsumId(consumId);
                record.setUserId(userId);
                record.setCreateTime(new Date());
                collectCardsService.saveOrUpdateRecord(record);

                CollectUserCard card = collectCardsService.getUserCardByCardId(userId, cardsCard.getId());
                if(null == card){
                    card = new CollectUserCard();
                    card.setUserId(userId);
                    card.setActivityId(activityId);
                    card.setCardId(cardsCard.getId());
                    card.setQuantity(1);
                }else{
                    card.setQuantity(card.getQuantity() + 1);
                }
                collectCardsService.saveOrUpdateUserCard(card);
            }

            return true;
        }
    }

}
